import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:katana_router/katana_router.dart';
import 'package:thal/backstage/blueprint/dynamic_print.dart';
import 'package:thal/backstage/control_room/global_state_provider.dart';
import 'package:thal/backstage/toolkit/utilities/asset_manifest.dart';
import 'package:thal/backstage/toolkit/utilities/color_palette.dart';
import 'package:thal/backstage/toolkit/utilities/dimension_rules.dart';
import 'package:thal/playbill/auth_sage/login_production.dart';
import 'package:thal/backstage/control_room/badge_room.dart';
import 'package:thal/playbill/community_forum/dynamic_production.dart';
import 'package:thal/playbill/profile_saga/badge_wall_production.dart';
import 'package:thal/playbill/profile_saga/edit_profile_production.dart';
import 'package:thal/playbill/profile_saga/follower_following_list_production.dart';
import 'package:thal/playbill/profile_saga/settings_production.dart';
import 'package:thal/playbill/profile_saga/upload_dynamic_production.dart';

part 'profile_production.page.dart';

/// 个人资料页面
@PagePath('/profile')
class ProfileProduction extends StatefulWidget {
  const ProfileProduction({super.key});

  @pageRouteQuery
  static RouteQuery query() => const _$ProfileProductionQuery().call();

  @override
  State<ProfileProduction> createState() => _ProfileProductionState();
}

class _ProfileProductionState extends State<ProfileProduction> {
  int _selectedTabIndex = 0;
  late PageController _pageController;

  @override
  void initState() {
    super.initState();
    _pageController = PageController();
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(AssetManifest.screenBackground),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Observer(
            builder: (_) {
              final userRoom = GlobalStateProvider.userRoomOf(context);

              // 未登录时显示提示信息
              if (!userRoom.isLoggedIn) {
                return _renderGuestContent(context);
              }

              // 已登录时显示完整内容
              return _renderAuthenticatedContent(context);
            },
          ),
        ),
      ),
      floatingActionButton: Observer(
        builder: (_) {
          final userRoom = GlobalStateProvider.userRoomOf(context);
          if (!userRoom.isLoggedIn) return SizedBox.shrink();

          return Padding(
            padding: EdgeInsets.only(bottom: 90.h),
            child: FloatingActionButton(
              onPressed: () {
                context.router.push(UploadDynamicProduction.query());
              },
              backgroundColor: ColorPalette.blue1,
              child: Icon(Icons.add, color: Colors.white, size: 32.sp),
            ),
          );
        },
      ),
    );
  }

  /// 渲染访客内容
  Widget _renderGuestContent(BuildContext context) {
    return Center(
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 40.w),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 装饰图片
            Image.asset(
              AssetManifest.panda,
              width: 200.w,
              height: 200.w,
              fit: BoxFit.contain,
            ),

            40.h.heightBox,

            // 提示信息
            Text('Please login to view profile', textAlign: TextAlign.center)
                .fontSize(20.sp)
                .textColor(ColorPalette.black)
                .arimo(weight: FontWeight.bold),

            16.h.heightBox,

            Text(
                  'Login to see your profile and posts',
                  textAlign: TextAlign.center,
                )
                .fontSize(14.sp)
                .textColor(ColorPalette.black.withValues(alpha: 0.6))
                .arimo(),

            40.h.heightBox,

            // 登录按钮
            Container(
              width: double.infinity,
              padding: EdgeInsets.symmetric(vertical: 16.h),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [ColorPalette.blue2, ColorPalette.blue1],
                ),
                borderRadius: BorderRadius.circular(30.r),
              ),
              child: Text('Go to Login', textAlign: TextAlign.center)
                  .fontSize(16.sp)
                  .textColor(ColorPalette.white)
                  .arimo(weight: FontWeight.w600),
            ).withTapEffect(
              onTap: () {
                context.router.push(LoginProduction.query());
              },
            ),
          ],
        ),
      ),
    );
  }

  /// 渲染已登录内容
  Widget _renderAuthenticatedContent(BuildContext context) {
    final userRoom = GlobalStateProvider.userRoomOf(context);
    final dynamicRoom = GlobalStateProvider.dynamicRoomOf(context);
    final followRoom = GlobalStateProvider.followRoomOf(context);
    final badgeRoom = GlobalStateProvider.badgeRoomOf(context);
    final currentUser = userRoom.fetchCurrentUser();

    if (currentUser == null) return SizedBox.shrink();

    final userDynamics = dynamicRoom.fetchDynamicsByUserId(currentUser.id);
    final imageDynamics =
        userDynamics.where((d) => d.mediaType == 'image').toList();
    final videoDynamics =
        userDynamics.where((d) => d.mediaType == 'video').toList();

    // 获取真实的统计数据
    final followersCount = followRoom.fetchFollowersCount(currentUser.id);
    final followingCount = followRoom.fetchFollowingCount(currentUser.id);

    return Stack(
      clipBehavior: Clip.none,
      children: [
        Column(
          children: [
            // 顶部标题栏（固定）
            _renderTopBar(context),

            60.h.heightBox,

            // 白色背景区域
            Expanded(
              child: Container(
                width: double.infinity,
                padding: EdgeInsets.only(top: 115.h),
                decoration: BoxDecoration(color: ColorPalette.white),
                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      // 勋章墙
                      _renderBadgeWall(context, badgeRoom, currentUser.id),

                      24.h.heightBox,

                      // Tab 选择器
                      _renderTabSelector(context),

                      16.h.heightBox,

                      // 动态内容区域
                      _renderDynamicContent(
                        context,
                        imageDynamics,
                        videoDynamics,
                      ),

                      100.h.heightBox, // 为浮动按钮留空间
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),

        // 头像在最外层 Stack 中，不受容器裁剪影响
        Positioned(
          top: 70.h,
          left: 0,
          right: 0,
          child: Center(
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    40.w.widthBox,
                    // 粉丝数据
                    GestureDetector(
                      onTap: () {
                        // 跳转到粉丝列表页面
                        context.router.push(
                          FollowerFollowingListProduction.query(
                            isFollowingList: false,
                          ),
                        );
                      },
                      child: Column(
                        children: [
                          Text('$followersCount')
                              .fontSize(16.sp)
                              .textColor(ColorPalette.black)
                              .arimo(weight: FontWeight.w700),
                          Text('Follower')
                              .fontSize(12.sp)
                              .textColor(const Color(0xFF999999))
                              .arimo(weight: FontWeight.w400),
                        ],
                      ),
                    ),
                    const Spacer(),
                    Column(
                      children: [
                        Container(
                          padding: EdgeInsets.all(6.w),
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            color: Color(0xFFB2E4FC),
                          ),
                          child: Container(
                            width: 100.w,
                            height: 100.w,
                            decoration: BoxDecoration(shape: BoxShape.circle),
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(100.r),
                              child: Image.asset(
                                currentUser.avatar,
                                fit: BoxFit.cover,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    const Spacer(),

                    // 关注数据
                    GestureDetector(
                      onTap: () {
                        // 跳转到关注列表页面
                        context.router.push(
                          FollowerFollowingListProduction.query(
                            isFollowingList: true,
                          ),
                        );
                      },
                      child: Column(
                        children: [
                          Text('$followingCount')
                              .fontSize(16.sp)
                              .textColor(ColorPalette.black)
                              .arimo(weight: FontWeight.bold),
                          Text('Following')
                              .fontSize(12.sp)
                              .textColor(
                                ColorPalette.black.withValues(alpha: 0.6),
                              )
                              .arimo(),
                        ],
                      ),
                    ),
                    40.w.widthBox,
                  ],
                ),
                // 中间用户名和签名
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text(
                          currentUser.username,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        )
                        .fontSize(20.sp)
                        .textColor(ColorPalette.black)
                        .arimo(weight: FontWeight.w700),
                    // 显示用户当前展示的勋章
                    Observer(
                      builder: (_) {
                        final displayedBadge = badgeRoom.getUserDisplayedBadge(
                          currentUser.id,
                        );
                        if (displayedBadge != null) {
                          return Row(
                            children: [
                              8.w.widthBox,
                              SizedBox(
                                width: 20.w,
                                height: 20.w,
                                child: Image.asset(
                                  displayedBadge.imageUrl,
                                  fit: BoxFit.contain,
                                ),
                              ),
                            ],
                          );
                        }
                        return SizedBox.shrink();
                      },
                    ),
                  ],
                ).wrapHorizontal(16.w),
                Text(
                      currentUser.signature,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    )
                    .fontSize(12.sp)
                    .textColor(const Color(0xFF999999))
                    .arimo(weight: FontWeight.w400)
                    .wrapHorizontal(16.w),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 渲染顶部标题栏
  Widget _renderTopBar(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      child: Row(
        children: [
          Text('Me')
              .fontSize(24.sp)
              .textColor(ColorPalette.black)
              .carterOne(weight: FontWeight.w700),
          const Spacer(),
          // 编辑按钮
          GestureDetector(
            onTap: () {
              context.router.push(EditProfileProduction.query());
            },
            child: Container(
              width: 40.w,
              height: 40.w,
              padding: EdgeInsets.all(8.w),
              decoration: BoxDecoration(
                color: ColorPalette.iconBg,
                shape: BoxShape.circle,
              ),
              child: Image.asset(AssetManifest.edit),
            ),
          ),
          12.w.widthBox,
          // 设置按钮
          GestureDetector(
            onTap: () {
              context.router.push(SettingsProduction.query());
            },
            child: Container(
              width: 40.w,
              height: 40.w,
              padding: EdgeInsets.all(8.w),
              decoration: BoxDecoration(
                color: ColorPalette.iconBg,
                shape: BoxShape.circle,
              ),
              child: Image.asset(AssetManifest.setting),
            ),
          ),
        ],
      ),
    );
  }

  /// 渲染勋章墙
  Widget _renderBadgeWall(
    BuildContext context,
    BadgeRoom badgeRoom,
    String userId,
  ) {
    // 获取所有勋章和用户拥有的勋章
    final allBadges = badgeRoom.fetchAllBadges();
    final userBadges = badgeRoom.fetchUserBadges(userId);
    final userBadgeIds =
        userBadges.map((userBadge) => userBadge.badgeId).toList();

    return GestureDetector(
      onTap: () {
        context.router.push(BadgeWallProduction.query());
      },
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Badge Wall')
                .fontSize(14.sp)
                .textColor(ColorPalette.black)
                .arimo(weight: FontWeight.w400),
            16.h.heightBox,
            SizedBox(
              height: 60.h,
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: allBadges.length,
                itemBuilder: (context, index) {
                  final badge = allBadges[index];
                  final hasBadge = userBadgeIds.contains(badge.id);

                  return Padding(
                    padding: EdgeInsets.only(right: 20.w),
                    child: SizedBox(
                      width: 50.w,
                      height: 50.w,
                      child: ColorFiltered(
                        colorFilter:
                            hasBadge
                                ? ColorFilter.matrix(<double>[
                                  1, 0, 0, 0, 0, // R
                                  0, 1, 0, 0, 0, // G
                                  0, 0, 1, 0, 0, // B
                                  0, 0, 0, 1, 0, // A
                                ])
                                : ColorFilter.matrix(<double>[
                                  0.2126, 0.7152, 0.0722, 0, 0, // 灰度转换
                                  0.2126, 0.7152, 0.0722, 0, 0,
                                  0.2126, 0.7152, 0.0722, 0, 0,
                                  0, 0, 0, 1, 0,
                                ]),
                        child: Image.asset(badge.imageUrl, fit: BoxFit.contain),
                      ),
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 渲染Tab选择器
  Widget _renderTabSelector(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          GestureDetector(
            onTap: () {
              setState(() {
                _selectedTabIndex = 0;
              });
              _pageController.animateToPage(
                0,
                duration: Duration(milliseconds: 300),
                curve: Curves.easeInOut,
              );
            },
            child: Container(
              padding: EdgeInsets.symmetric(vertical: 12.h, horizontal: 40.w),
              decoration: BoxDecoration(
                color:
                    _selectedTabIndex == 0
                        ? ColorPalette.blue1
                        : const Color(0xFFF5F5F5),
                borderRadius: BorderRadius.circular(24.r),
              ),
              child: Text('Photo', textAlign: TextAlign.center)
                  .fontSize(16.sp)
                  .textColor(
                    _selectedTabIndex == 0 ? Colors.white : ColorPalette.black,
                  )
                  .arimo(weight: FontWeight.w600),
            ),
          ),
          12.w.widthBox,
          GestureDetector(
            onTap: () {
              setState(() {
                _selectedTabIndex = 1;
              });
              _pageController.animateToPage(
                1,
                duration: Duration(milliseconds: 300),
                curve: Curves.easeInOut,
              );
            },
            child: Container(
              padding: EdgeInsets.symmetric(vertical: 12.h, horizontal: 40.w),
              decoration: BoxDecoration(
                color:
                    _selectedTabIndex == 1
                        ? ColorPalette.blue1
                        : const Color(0xFFF5F5F5),
                borderRadius: BorderRadius.circular(24.r),
              ),
              child: Text('Video', textAlign: TextAlign.center)
                  .fontSize(16.sp)
                  .textColor(
                    _selectedTabIndex == 1 ? Colors.white : ColorPalette.black,
                  )
                  .arimo(weight: FontWeight.w600),
            ),
          ),
        ],
      ),
    );
  }

  /// 渲染动态内容区域
  Widget _renderDynamicContent(
    BuildContext context,
    List<DynamicPrint> imageDynamics,
    List<DynamicPrint> videoDynamics,
  ) {
    // 计算所需高度
    final maxItemCount =
        imageDynamics.length > videoDynamics.length
            ? imageDynamics.length
            : videoDynamics.length;

    // 根据动态数量计算高度
    final rowCount = (maxItemCount / 2).ceil();
    final itemHeight =
        (MediaQuery.of(context).size.width - 40.w - 12.w) / 2 * (298 / 171);
    final pageHeight = rowCount * itemHeight + (rowCount - 1) * 12.w + 100.h;

    return SizedBox(
      height: pageHeight.clamp(100.h, double.infinity),
      child: PageView.builder(
        controller: _pageController,
        itemCount: 2,
        physics: const NeverScrollableScrollPhysics(),
        onPageChanged: (index) {
          setState(() {
            _selectedTabIndex = index;
          });
        },
        itemBuilder: (context, index) {
          if (index == 0) {
            // 图片动态
            return _buildImagePage(imageDynamics);
          } else {
            // 视频动态
            return _buildVideoPage(videoDynamics);
          }
        },
      ),
    );
  }

  /// 构建图片动态页面
  Widget _buildImagePage(List<DynamicPrint> dynamics) {
    if (dynamics.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.image_outlined,
              size: 64.sp,
              color: ColorPalette.black.withValues(alpha: 0.3),
            ),
            8.h.heightBox,
            Text('No image posts yet')
                .fontSize(14.sp)
                .textColor(ColorPalette.black.withValues(alpha: 0.6))
                .arimo(),
          ],
        ),
      );
    }

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: GridView.builder(
        physics: const NeverScrollableScrollPhysics(),
        shrinkWrap: true,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          mainAxisSpacing: 12.w,
          crossAxisSpacing: 12.w,
          childAspectRatio: 171 / 298,
        ),
        itemCount: dynamics.length,
        itemBuilder: (context, index) {
          final dynamic = dynamics[index];
          return _buildDynamicItem(dynamic, true);
        },
      ),
    );
  }

  /// 构建视频动态页面
  Widget _buildVideoPage(List<DynamicPrint> dynamics) {
    if (dynamics.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.videocam_outlined,
              size: 64.sp,
              color: ColorPalette.black.withValues(alpha: 0.3),
            ),
            8.h.heightBox,
            Text('No video posts yet')
                .fontSize(14.sp)
                .textColor(ColorPalette.black.withValues(alpha: 0.6))
                .arimo(),
          ],
        ),
      );
    }

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: GridView.builder(
        physics: const NeverScrollableScrollPhysics(),
        shrinkWrap: true,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          mainAxisSpacing: 12.w,
          crossAxisSpacing: 12.w,
          childAspectRatio: 171 / 298,
        ),
        itemCount: dynamics.length,
        itemBuilder: (context, index) {
          final dynamic = dynamics[index];
          return _buildDynamicItem(dynamic, false);
        },
      ),
    );
  }

  /// 构建动态项
  Widget _buildDynamicItem(DynamicPrint dynamic, bool isImage) {
    // 获取用户信息和点赞状态
    final userRoom = GlobalStateProvider.userRoomOf(context);
    final publisher = userRoom.fetchUserById(dynamic.userId);
    final currentUser = userRoom.fetchCurrentUser();
    final isLiked =
        currentUser != null && dynamic.likes.contains(currentUser.id);

    // 根据类型选择图片URL
    String imageUrl;
    if (isImage) {
      // 图片类型：使用mediaUrls
      imageUrl =
          dynamic.mediaUrls.isNotEmpty
              ? dynamic.mediaUrls[0]
              : AssetManifest.panda;
    } else {
      // 视频类型：使用thumbnailUrls（缩略图）
      imageUrl =
          dynamic.thumbnailUrls.isNotEmpty && dynamic.thumbnailUrls[0] != null
              ? dynamic.thumbnailUrls[0]!
              : (dynamic.mediaUrls.isNotEmpty
                  ? dynamic.mediaUrls[0]
                  : AssetManifest.panda);
    }

    return GestureDetector(
      onTap: () {
        context.router.push(DynamicProduction.query(dynamicId: dynamic.id));
      },
      child: Container(
        clipBehavior: Clip.antiAlias,
        decoration: BoxDecoration(
          color: ColorPalette.white,
          borderRadius: BorderRadius.circular(12.r),
          boxShadow: [
            BoxShadow(
              color: ColorPalette.black.withValues(alpha: 0.05),
              blurRadius: 8,
              offset: Offset(0, 2.h),
            ),
          ],
        ),
        child: Column(
          children: [
            // 图片/视频区域
            Expanded(
              flex: 6,
              child: Stack(
                clipBehavior: Clip.none,
                children: [
                  SizedBox(
                    width: double.infinity,
                    child: Image.asset(imageUrl, fit: BoxFit.cover),
                  ),
                  // 视频播放图标
                  if (!isImage)
                    Positioned.fill(
                      child: Center(
                        child: Icon(
                          Icons.play_arrow_rounded,
                          size: 48.sp,
                          color: Colors.white,
                        ),
                      ),
                    ),
                ],
              ),
            ),

            // 标题和信息区域
            Expanded(
              flex: 2,
              child: Padding(
                padding: EdgeInsets.all(8.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    // 标题
                    Text(
                          dynamic.title,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        )
                        .fontSize(12.sp)
                        .textColor(ColorPalette.black)
                        .arimo(weight: FontWeight.w600),

                    8.h.heightBox,

                    // 用户信息和点赞按钮
                    Row(
                      children: [
                        // 用户头像
                        Container(
                          width: 24.w,
                          height: 24.w,
                          decoration: BoxDecoration(shape: BoxShape.circle),
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(12.r),
                            child: Image.asset(
                              publisher?.avatar ?? AssetManifest.avatar1,
                              fit: BoxFit.cover,
                            ),
                          ),
                        ),

                        8.w.widthBox,

                        // 用户名
                        Expanded(
                          child: Text(
                                publisher?.username ?? 'Unknown',
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              )
                              .fontSize(10.sp)
                              .textColor(
                                ColorPalette.black.withValues(alpha: 0.6),
                              )
                              .arimo(weight: FontWeight.w400),
                        ),

                        // 点赞按钮
                        Image.asset(
                          isLiked ? AssetManifest.like : AssetManifest.unlike,
                          width: 16.w,
                          height: 16.w,
                          color:
                              isLiked ? ColorPalette.blue1 : ColorPalette.black,
                        ).withTapEffect(
                          onTap: () {
                            if (currentUser == null) return;
                            final dynamicRoom =
                                GlobalStateProvider.dynamicRoomOf(context);
                            dynamicRoom.toggleLike(dynamic.id, currentUser.id);
                          },
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
